<template>
  <div class="child" style="padding: 20px 30px;">
    <el-row>
      <el-col :span="18">
        <el-button type="success" @click="add(1)">添加</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <div class="tableBox">
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
      >
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="link" label="跳转路径" />
        <el-table-column label="预览">
          <template slot-scope="scope">
            <el-image
              style="width: auto; height: 60px"
              :src="scope.row.img"
              :preview-src-list="[scope.row.img]"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" show-overflow-tooltip>
          <template slot-scope="scope">
            <div class="btnList">
              <el-button type="text" @click="edit(scope.row)">编辑</el-button>
              <el-button type="text" @click="del(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="fenye">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- *************对话框开始************* -->
    <el-dialog
      title="管理轮播图"
      :visible.sync="addFormDialog"
      width="40%"
      center
      :close-on-click-modal="false"
    >
      <!-- 新增轮播图 -->
      <div>
        <el-form ref="ruleForm" :model="addForm" label-width="80px" :rules="typeRules" label-position="top">
          <el-form-item label="标题" prop="title">
            <el-input v-model="addForm.title" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="链接" prop="link">
            <el-input v-model="addForm.link" placeholder="请输入链接" />
          </el-form-item>
          <el-form-item label="图片" prop="img">
            <el-upload
              class="avatar-uploader"
              :action="action"
              :headers="myHeaders"
              :show-file-list="false"
              :on-success="(res)=>{handleAvatarSuccess(res,'img')}"
            >
              <img v-if="addForm.img" :src="addForm.img" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
            <el-input v-model="addForm.img" style="margin-top:20px;" placeholder="请输入图片地址" />
            <span class="tips">请上传图片或输入图片地址，建议尺寸：960*448px</span>
          </el-form-item>
          <el-form-item label="点击打开方式">
            <el-radio-group v-model="addForm.type">
              <el-radio :label="1">当前页打开</el-radio>
              <el-radio :label="2">新页面打开</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addFormDialog = false">取 消</el-button>
        <el-button type="primary" @click="addForm_enter('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  swiperList,
  swiperAdd,
  swiperDelete,
  swiperDetail
} from '@/api/swiper'
import { uploadUrl, token } from '@/utils/request'
export default {
  data () {
    return {
      action: uploadUrl,
      myHeaders: {
        'Authorization-admin': token
      },
      formInline: {
        page: '1', // 当前页
        pageSize: '10' // 每页记录数
      },
      total: 1,
      tableData: [],
      currentPage: 1,
      typeState: 1,
      addForm: {
        id: '',
        title: '',
        link: '',
        img: '',
        type: 1
      },
      addFormDialog: false,
      typeRules: {
        img: [
          { required: true, message: '图片不能为空', trigger: 'blur' }
        ],
      },
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.getAll(this.formInline)
  },
  // 方法集合
  methods: {
    // 图片上传回调
    handleAvatarSuccess (response, key) {
      const { url } = response.data
      this.addForm[key] = url
      this.$forceUpdate()
    },
    handleSizeChange (val) {
      this.formInline.pageSize = val
      this.getAll(this.formInline)
    },
    handleCurrentChange (val) {
      this.formInline.page = val
      this.getAll(this.formInline)
    },
    // 新增轮播图
    add (index) {
      this.typeState = 1
      if (index === 1) {
        this.addForm = {
          id: '',
          title: '',
          link: '',
          img: '',
          type: 1
        }
        this.addFormDialog = true
      }
    },
    // 确认新增轮播图
    addForm_enter (ruleForm) {
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          if (this.typeState) {
            console.log(this.addForm)
            swiperAdd(this.addForm).then(res => {
              console.log(res)
              if (res.code === '') {
                this.$message({
                  message: '新增成功',
                  type: 'success'
                })
              }
              this.getAll(this.formInline)
              this.addFormDialog = false
            })
          } else {
            swiperAdd(this.addForm).then(res => {
              console.log(res)
              if (res.code === '') {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
              }
              this.getAll(this.formInline)
              this.addFormDialog = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 编辑轮播图
    edit (row) {
      this.typeState = 0
      this.addFormDialog = true
      console.log(row)
      swiperDetail({ id: row.id }).then(res => {
        console.log(res, 'res')
        this.addForm = res.data
        console.log(this.addForm)
        // this.addForm.roleIds = [1];
      })
    },
    // 删除轮播图
    async del (row) {
      if (row) {
        const res = await swiperDelete({ ids: row.id })
        if (res.code === '') {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        }
        this.getAll(this.formInline)
      } else if (!this.multipleSelection || this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择数据'
        })
        return
      } else {
        const res = await swiperDelete({ ids: this.multipleSelection })
        if (res.code === '') {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        }
        this.getAll(this.formInline)
      }
    },
    // 初始化查询所有数据
    async getAll (formInline) {
      const res = await swiperList(formInline)
      this.tableData = res.data.list
      this.total = res.data.total
    }
  }
};
</script>
      <style lang="less" scoped>
  .flex {
    display: flex;
    align-items: center;
    i {
      font-size: 26px;
      margin-left: 10px;
    }
  }
  .tableBox {
    padding-top: 20px;
  }
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 120px;
    height: 120px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
    border: 1px dashed #d9d9d9;
  }
  .avatar {
    width: 120px;
    height: auto;
    display: block;
  }
</style>

